/*
Copyright 2025 PerfXLab (Beijing) Technologies Co., Ltd.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "OpenSpB_Error.h"
#include <stdio.h>
#include <stdlib.h>
#include <execinfo.h>
#include <signal.h>
#include <unistd.h>

void OpenSpB_error(char *errorMsg);

void handler(int sig);

void OpenSpB_error(char *errorMsg)
{
    void *array[10];
    size_t size;

    // get void*'s for all entries on the stack
    size = backtrace(array, 10);

    // print out all the frames to stderr
    fprintf(stderr, "\033[31m[ FATAL ERROR ] \033[0m:: %s", errorMsg);
    backtrace_symbols_fd(array, size, STDERR_FILENO);
    // fprintf(stderr, "\033[31m[ FATAL ERROR ] \033[0m:: %s", errorMsg);
    exit(-1);
}

void handler(int sig)
{
    void *array[10];
    size_t size;

    // get void*'s for all entries on the stack
    size = backtrace(array, 10);

    // print out all the frames to stderr
    fprintf(stderr, "Error: signal %d:\n", sig);
    backtrace_symbols_fd(array, size, STDERR_FILENO);
    exit(1);
}

void OpenSpB_Error(char *errorMsg, char *filename, const int line)
{
    fprintf(stderr, "\033[31m[ FATAL ERROR ] \033[0m%s at %s:%d\n", errorMsg, filename, line);
    exit(-1);
}